import { useCallback } from 'react';
import { Button } from 'antd-mobile';
import { TextWidget, getMessage } from '@inbiz/react';
import styles from './index.less';

export interface SelectBarProps {
  filterKey: string;
  multiple: boolean;
  data: any[];
  selectedId: any[];
  selected: any[];
  allSelected: any[];
  setSelected: (sels: any[]) => void;
  onOk: () => void;
  onCancel: () => void;
}

export default function SelectBar(props: SelectBarProps) {
  let isSelectedAll = props.data.length
    ? props.data.every((v) => {
        return props.selectedId.includes(v.key);
      })
    : false;
  const onToggleSelectAll = useCallback(() => {
    if (!isSelectedAll) {
      //全选
      let appendData: any[] = [];
      props.data.forEach((row) => {
        if (!props.selectedId.includes(row.key)) {
          appendData.push(row);
        }
      });
      props.setSelected([...props.allSelected, ...appendData]);
    } else {
      //全不选
      let spliceData: any[] = [];
      props.data.forEach((row) => {
        if (props.selectedId.includes(row.key)) {
          spliceData.push(row);
        }
      });
      props.setSelected([
        ...props.allSelected.filter((v) => {
          if (!v.key.startsWith(props.filterKey)) {
            return true;
          }
          return spliceData.every((item) => {
            item.key != v.key;
          });
        }),
      ]);
    }
  }, [
    isSelectedAll,
    props.allSelected,
    props.data,
    props.selectedId,
    props.selected,
    props.filterKey,
  ]);
  return (
    <div className={styles.selectedCountRow}>
      <div className={styles.selectedCountRowLeft}>
        {props.multiple ? (
          <span
            className={styles.selectAll}
            onClick={(e) => {
              onToggleSelectAll();
            }}
          >
            {isSelectedAll
              ? getMessage('WapMemberSelect.lang.unSelectAll')
              : getMessage('WapMemberSelect.lang.selectAll')}
          </span>
        ) : null}
        <span className={styles.selected}>
          <TextWidget>WapMemberSelect.lang.seected1</TextWidget>
          {props.selectedId.length}
          <TextWidget>WapMemberSelect.lang.seected2</TextWidget>
          {props.allSelected.length}
          <TextWidget>WapMemberSelect.lang.seected3</TextWidget>
        </span>
      </div>
      <Button
        style={{
          background: 'var(--inbiz-color-primary)',
          color: 'var(--inbiz-color-white)',
          fontSize: 16,
        }}
        size="small"
        onClick={(e) => {
          props.onOk();
        }}
      >
        {getMessage('WapMemberSelect.lang.action.ok')}
      </Button>
    </div>
  );
}
